<?php

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Log;

class QueryListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  QueryExecuted  $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        try{
            $connectionName = $event->connectionName;
            $sql = str_replace("?", "'%s'", $event->sql);
            foreach ($event->bindings as $i => $binding) {
                if (is_object($binding) && method_exists($binding, 'format')) {
                    $event->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                } else {
                    if (is_string($binding)) {
                        $event->bindings[$i] = "'$binding'";
                    }
                }
            }
            if (strpos($sql, '%s')) {
                $query = vsprintf($sql, $event->bindings);
            } else {
                $query = $sql;
            }
            $query = str_replace('7fa8282ad93047a4d6fe6111c93b308a', '%', $query);
            $log = 'time_cost[' . $event->time . 'ms] db[' . $connectionName . ']  query[' . $query . ']';
            if (strtoupper(substr(trim($query), 0, 6)) == 'SELECT') {
                Log::channel('sqlr')->info($log);
            } else {
                Log::channel('sqlcud')->info($log);
            }

            if ($event->time > 100) {
                Log::channel('sqlslow')->info($log);
            }
//            }
        }catch (Exception $exception){

        }
    }
}
